In a multithreaded environment, the Object.wait(…)
, as well as Condition.await(…)
and similar methods are used to pause
the execution of a thread until the thread is awakened. A thread is typically awakened when it is notified, signaled, or interrupted, usually because
of an event in another thread requiring some subsequent action by the waiting thread.
However, a thread may be awakened despite the desired condition not being met or the desired event not having happened. This is referred to as
"spurious wakeups" and may be caused by underlying platform semantics. In other words, a thread may be awakened due to reasons that have nothing to do
with the business logic. Hence, the assumption that the desired condition is met or the desired event occurred after a thread is awakened does not
always hold.
According to the documentation of the Java Condition
interface [1]:
When waiting upon a Condition
, a "spurious wakeup" is permitted to occur, in general, as a concession to the underlying platform
semantics. This has little practical impact on most application programs as a Condition should always be waited upon in a loop, testing the state
predicate that is being waited for. An implementation is free to remove the possibility of spurious wakeups but it is recommended that applications
programmers always assume that they can occur and so always wait in a loop.
The same advice is also found for the Object.wait(…)
method [2]:
[…] waits should always occur in loops, like this one:
synchronized (obj) {
while (<condition does not hold>){
obj.wait(timeout);
}
... // Perform action appropriate to condition
}